package com.zeus.core.config.spring;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * spring上下文
 *
 * @author f1ybear_wang  2022/5/7 11:05
 */
public class ZeusApplicationContextHelper implements ApplicationContextAware {
    /**
     * Spring上下文
     */
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        applicationContext = context;
    }

    public static ApplicationContext getApplicationContext(){
       return applicationContext;
    }

    /**
     * 根据类型获取bean
     *
     * @param clazz 类型
     * @return Bean
     */
    public static <T> T popBean(Class<T> clazz) {
        if (applicationContext == null) {
            return null;
        }
        return applicationContext.getBean(clazz);
    }

    /**
     * 根据名称获取bean
     *
     * @param name bean名称
     * @return Bean
     */
    public static <T> T popBean(String name) {
        if (applicationContext == null) {
            return null;
        }
        return (T)applicationContext.getBean(name);
    }
}
